package services

import (
	"football/src/utils"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/spf13/viper"
	"time"
)

func Uploadfile(c *gin.Context) {
	form, err := c.MultipartForm()
	if err != nil {
		utils.RespFail(c.Writer, "解析表单数据失败")
		utils.Error("解析表单数据失败", err)
		return
	}

	// 获取上传的文件
	files := form.File["file"] // 注意这里要和前端的 `name` 相匹配
	if len(files) == 0 {
		utils.RespFail(c.Writer, "未上传文件")
		return
	}

	uploadPath := make([]string, 0, len(files)) // 动态切片，长度与上传文件数量相同
	absPath := make([]string, 0, len(files))    // 动态切片，长度与上传文件数量相同
	ip := "http://" + viper.GetString("minio.ip")
	for key, file := range files {
		objectName := time.Now().Format("20060102") + "/" + uuid.New().String()
		err := utils.UploadToMinio(objectName, file)
		if err != nil {
			utils.RespFail(c.Writer, "上传数据集失败")
			utils.Error("上传数据集失败", err)
			return
		}
		uploadPath = append(uploadPath, "/"+viper.GetString("minio.bucket")+"/"+objectName)
		absPath = append(absPath, ip+uploadPath[key])
	}

	response := gin.H{
		"ipPath":     ip,
		"absPath":    absPath, // 假设 files 存储的是绝对路径
		"uploadPath": uploadPath,
	}
	utils.RespOk(c.Writer, response, "上传文件成功")
}
